package com.dataart.productshop.service.impl;

import com.dataart.productshop.dao.PictureDao;
import com.dataart.productshop.file.utils.SavePicture;
import com.dataart.productshop.model.FileInfo;
import com.dataart.productshop.model.Picture;
import com.dataart.productshop.service.PictureManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.util.List;

@Service("pictureManager")
@Transactional
public class PictureManagerImpl extends BaseManagerImpl<Picture> implements
		PictureManager {

	private PictureDao pictureDao; //TODO: remove. this dao has to be already incapsulated in BaseManagerImpl
    private SavePicture savePictureUtil;

	
	@Autowired //let's try to remove all this shit and add one @Autowired to BaseManagerImpl.dao
	public void setPictureDao(PictureDao pictureDao) {
		this.pictureDao = pictureDao;
        setBaseDao(pictureDao);
	}
	
	@Override
	public void savePicture(Picture picture) {
		pictureDao.save(picture);
	}

	@Override
	public Picture getPictureById(Long id) {
		return pictureDao.getById(id);
	}

	@Override
	public void delete(Long id) {
		pictureDao.delete(id);

	}

    @Override
    public boolean savePictures(String folderPath, FileInfo fileInfo, CommonsMultipartFile... pictures) {
        for(CommonsMultipartFile picture:pictures){
            if(!picture.isEmpty() && savePictureUtil.savePictures(picture,folderPath)){
                String filePath = folderPath + "/" +picture.getOriginalFilename();
                save(new Picture(filePath, fileInfo));
            }else{
                if(pictures.length < 2){
                    return false;
                } else {
                    System.err.println("error while saving " + picture.getOriginalFilename());
                }
            }
        }
        return true;
    }

	@Override
	public List<Picture> getPictureByFileInfo(FileInfo fileInfo) {
		if(fileInfo == null || fileInfo.getId() == null){
			System.err.println("can't get pictures cause of fileInfo == null OR have no ID");
			return null;
		}
		return pictureDao.getPictureByFileInfo(fileInfo);
	}


}
